package com.example.easyexcel.exports.custom_export.CustomFormulation;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.example.easyexcel.exports.custom_export.CustomFormulation.strategy.ColumnStyleStrategy;
import com.example.easyexcel.exports.customized.util.ExportUtil;
import lombok.Cleanup;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 定制导出：制剂配方
 **/
@Service
public class CustomFormulationExportService {
//    @Autowired // todo
//    private ModuleDataService moduleDataService;

    private static String FORMULA_KEY = "formulaTableData";
    private static String FILE_NAME = "制剂配方";
    private List<Integer> titleRowIndex;

    public void export(ExportDto exportDto) {
        titleRowIndex = new ArrayList();
        // 获取数据
        List<?> datas = getData(exportDto);
        // 重组数据
        List<List<?>> rowDatas = dealData(datas, exportDto);
        // 执行导出
        String fileName = StrUtil.emptyToDefault(exportDto.getModuleName(), FILE_NAME);
        doExport(rowDatas, fileName);
    }

    private List<?> getData(ExportDto dto) {
        List list = null;
        // todo
//        list = moduleDataService.selectListByQuery(
//                Wrappers.lambdaQuery(ModuleData.class)
//                        .eq(ModuleData::getBusId, dto.getBusId())
//                        .eq(ModuleData::getBusNo, dto.getBusNo())
//        );
        return list;
    }

    private List<List<?>> dealData(List<?> moduleDatas, ExportDto exportDto) {
        List<List<?>> rowDatas = new LinkedList<>();
        String busData = null;
        if (CollUtil.isNotEmpty(moduleDatas)) {
            for (int i = 0; i < moduleDatas.size(); i++) {
//                ModuleData moduleData = (ModuleData) moduleDatas.get(i);// todo
//                busData = moduleData.getBusData();
                if (JSONUtil.isJsonArray(busData)) {

                    JSONArray batchs = JSONUtil.parseArray(busData);
                    for (int i1 = 0; i1 < batchs.size(); i1++) {
                        JSONObject batch = JSONUtil.parseObj(batchs.get(i1));
                        // 设置 制剂批次 头
                        rowDatas.add(exportDto.getHeadersOfBatch());
                        titleRowIndex.add(rowDatas.size() - 1);
                        // 设置 制剂批次 数据
                        List<Object> batchData = new LinkedList<>();
                        for (String ref : exportDto.getHeaderRefsOfBatch()) {
                            batchData.add(batch.getStr(ref));
                        }
                        rowDatas.add(batchData);
                        rowDatas.add(null);
                        rowDatas.add(null);
                        // 配方
                        if (JSONUtil.isJsonArray(batch.getStr(FORMULA_KEY))) {
                            JSONArray jarr = batch.getJSONArray(FORMULA_KEY);
                            // 设置 配方 头
                            rowDatas.add(exportDto.getHeadersOfFormula());
                            titleRowIndex.add(rowDatas.size() - 1);
                            // 设置 配方 数据
                            for (int i2 = 0; i2 < jarr.size(); i2++) {
                                JSONObject formula = JSONUtil.parseObj(jarr.get(i2));
                                List<Object> formulaData = new LinkedList<>();
                                formulaData.add(i2 + 1 + "");
                                for (String ref : exportDto.getHeaderRefsOfFormula()) {
                                    formulaData.add(formula.getStr(ref));
                                }
                                rowDatas.add(formulaData);
                            }
                            rowDatas.add(null);
                            rowDatas.add(null);
                        }
                    }
                }
            }
        }
        return rowDatas;
    }

    @SneakyThrows
    private void doExport(List<List<?>> rowDatas, String fileName) {
        int sheetIndex = 0;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        ExportUtil.setExcelRespProp(response, ExportUtil.createFileName(fileName));
        @Cleanup("finish") ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).autoCloseStream(true).build();

        WriteSheet writeSheet = EasyExcel.writerSheet(sheetIndex++, "Sheet" + sheetIndex)
                //.head(headers)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerWriteHandler(new ColumnStyleStrategy(titleRowIndex))
                .build();
        excelWriter.write(rowDatas, writeSheet);
    }

}
